﻿using StarryEdge.Core.Device;
using StarryEdge.Core.Models;
using StarryEdge.Core;
using StarryEdge.Devices.MeterDevice.Testers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StarryEdge.Devices.MeterDevice
{
    public class NoProtocolInt : NormalDeviceBase, IDeviceInteraction<int>
    {
        public NoProtocolInt(ICommunication com, IStarryEdgeLog edgeLog, Func<DeviceInfoModel, IDevice, bool> func) : base(com, edgeLog, func)
        {
        }

        public void Close() => _com.Close();

        public bool Open() => _com.Open();

        public TValue ReadSingle<TValue>(int address, int length = 3)
        {
            for (int i = 0; i < length; i++)
            {
                try
                {
                    if (_com.Receive() is TValue bytes)
                    {
                        return bytes;
                    }
                    return default;
                }
                catch (Exception ex)
                {
                    _edgeLog.LogRun($"[{nameof(ST5520)}] 异常：{ex}", Core.Enums.LogLevel.Warning);
                    if (_func.Invoke(_com.DeviceInfo, this))
                    {
                        return default;
                    }
                }
            }
            return default;
        }

        public bool WriteSingle(int address, object value, int length)
        {
            if (value is byte[] bytes)
            {
                for (int i = 0; i < length; i++)
                {
                    try
                    {
                        _com.Send(bytes);
                        return true;
                    }
                    catch (Exception ex)
                    {
                        _edgeLog.LogRun($"[{nameof(ST5520)}] 异常：{ex}", Core.Enums.LogLevel.Warning);
                        if (_func.Invoke(_com.DeviceInfo, this))
                        {
                            return default;
                        }
                    }
                }
            }
            return false;
        }
    }
}
